package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.dto.SetMealDto;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SetMealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;

    @Transactional
    @Override
    public void saveWithDish(SetMealDto setMealDto) {
        //A. 保存套餐基本信息
        this.save(setMealDto);
        //B. 获取套餐关联的菜品集合，并为集合中的每一个元素赋值套餐ID(setmealId)
        List<SetmealDish> setmealDishes = setMealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setMealDto.getId());
        }
        
        //C. 批量保存套餐关联的菜品集合
        setmealDishService.saveBatch(setmealDishes);
    }

    //* 删除套餐，同时需要删除套餐和菜品的关联数据
    //#统计3个套餐下是否有正在启用的套餐, 如果有无法删除
    //SELECT COUNT(id) FROM setmeal WHERE id IN('1415580119015145474','234234','44444') AND STATUS=1
    //#删除三个套餐
    //DELETE FROM setmeal WHERE id IN(1,2,3);
    //删除三个套餐下的所有菜品
    //DELETE FROM dish WHERE category_id IN(1,2,3);
    @Override
    @Transactional
    public void removeWithDish(List<Long> ids) {
        //A. 查询该批次套餐中是否存在售卖中的套餐, 如果存在, 不允许删除
        LambdaQueryWrapper<Setmeal> lqw1=new LambdaQueryWrapper<>();
        lqw1.in(Setmeal::getId,ids);   //WHERE id IN('1415580119015145474','234234','44444')
        lqw1.eq(Setmeal::getStatus,1);//AND STATUS=1
        int count=this.count(lqw1); //SELECT COUNT(id) FROM setmeal WHERE id IN('1415580119015145474','234234','44444') AND STATUS=1
        if(count>0){
            //不能删除,抛出业务异常
            throw new CustomException("套餐正在售卖中,不能删除");
        }
        //B. 删除套餐数据
        this.removeByIds(ids); //MP自带的根据ID批量删除功能
        //C. 删除套餐关联的菜品数据  //DELETE FROM dish WHERE category_id IN(1,2,3);
        LambdaQueryWrapper<SetmealDish> lqw2=new LambdaQueryWrapper<>();
        lqw2.in(SetmealDish::getSetmealId,ids); // WHERE category_id IN(1,2,3);
        //删除关系表中的数据
        setmealDishService.remove(lqw2);

    }
}

















